#include "dateitemdelegate.h"

#include <QDateTimeEdit>

DateItemDelegate::DateItemDelegate(QObject* parent) :QItemDelegate(parent) {

}

QWidget *DateItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QDateTimeEdit *editor = new QDateTimeEdit(parent);
    editor->setDisplayFormat("yyyy-MM-dd");
    editor->setCalendarPopup(true);//以下拉菜单方式显示
    editor->installEventFilter(const_cast<DateItemDelegate*>(this));//安装事件过滤器,
    return editor;
}

void DateItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString dateStr = index.model()->data(index).toString();
    QDate date = QDate::fromString(dateStr,Qt::ISODate);
    QDateTimeEdit *edit = static_cast<QDateTimeEdit*>(editor);
    edit->setDate(date);
}

void DateItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

void DateItemDelegate::setModelData(QWidget *editor, QAbstractItemModel* model, const QModelIndex &index)
{
    QDateTimeEdit *edit = static_cast<QDateTimeEdit*>(editor);
    QDate date = edit->date();
    model->setData(index,QVariant(date.toString(Qt::ISODate)));
}
